package cn.gov.pbc.tims.controller;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.gov.pbc.tims.entity.Fileup;
import cn.gov.pbc.tims.entity.User;
import cn.gov.pbc.tims.service.CommonService;
import cn.gov.pbc.tims.util.Operator;
import cn.gov.pbc.tims.util.Result;

@Controller
@RequestMapping("/fileController")
public class FileController {
	@Autowired
	private Operator operator;
	@Autowired
	private CommonService commonService;
	
	@RequestMapping(value="uploadPic")
	public @ResponseBody String uploadPic(
			HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file,HttpServletResponse response){
		String fileUrl = "";
		
		Fileup fileup = upload(request,file,response,"fileUpload");
		
		response.setContentType("text/plain;charset=UTF-8");
		
		fileUrl = String.valueOf(request.getRequestURL());
		String contextPath = request.getSession().getServletContext().getContextPath();
		fileUrl = fileUrl.substring(0, fileUrl.indexOf(contextPath) + contextPath.length());
		
		
		fileUrl += "/fileUpload/" + fileup.getFinalName();
		return fileUrl;
	}
	
	@RequestMapping(value="uploadExcel")
	public @ResponseBody String uploadExcel(
			HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file,HttpServletResponse response){
		String fileUrl = "";
		
		Fileup fileup = upload(request,file,response,"excelUpload");
		
		response.setContentType("text/plain;charset=UTF-8");
		
		fileUrl = request.getSession().getServletContext().getRealPath("/");
		
		fileUrl += "excelUpload\\" + fileup.getFinalName();
		
		return fileUrl;
	}
	@RequestMapping(value="uploadFile")
	public @ResponseBody Fileup uploadFile(
			HttpServletRequest request,
			@RequestParam(value = "upload_file", required = false) MultipartFile file,HttpServletResponse response){
		String fileUrl = "";
		
		Fileup fileup = upload(request,file,response,"upload");
		
		//response.setContentType("text/plain;charset=UTF-8");
		
		//fileUrl = request.getSession().getServletContext().getRealPath("/");
		
		//fileUrl += "upload\\" + fileup.getFinalName();
		
		return fileup;
	}
	private Fileup upload(HttpServletRequest request,
			@RequestParam(value = "upload_file", required = false) MultipartFile file,HttpServletResponse response,String dirName){
		
		Fileup fileup=new Fileup();
		try {
			String path = request.getSession().getServletContext().getRealPath("/" + dirName + "/");//指代根目录下的excelUpload目录
			
			//System.out.println(path);
			
			String fileName = "";
			
			if (null != file){
				fileName = file.getOriginalFilename();
			}
			DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");		
			//DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String str = format.format(Calendar.getInstance().getTime());
			//重命名文件名为 java.util.uuid 生成的随机串  + 后缀 ——建波提供
			//String saveFileName = UUID.randomUUID().toString() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
			String saveFileName = fileName.substring(0,fileName.lastIndexOf("."))+"By"+operator.getUser().getName()+str+"." + fileName.substring(fileName.lastIndexOf(".") + 1);		
			//System.out.println(saveFileName);
			
			File targetFile = new File(path, saveFileName);
			
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			
			file.transferTo(targetFile);
			
			String dispName=fileName;		
			fileup.setOrigName(fileName);
			fileup.setFinalName(saveFileName);
			fileup.setDispName(dispName);
			fileup.setPath(dirName+File.separator);
			fileup.setCreatedDate(Calendar.getInstance().getTime());
			User op = operator.getUser();
			fileup.setCreator(op.getName());
			fileup.setCreatorCode(op.getCode());
			fileup.setDeptId(op.getDeptId());
			fileup.setJgId(op.getJgId());
			commonService.save(fileup);
			/*
			response.setContentType("text/plain;charset=UTF-8");
			
			fileUrl = String.valueOf(request.getRequestURL());
			String contextPath = request.getSession().getServletContext().getContextPath();
			fileUrl = fileUrl.substring(0, fileUrl.indexOf(contextPath) + contextPath.length());
						
			fileUrl += "/excelUpload/" + saveFileName;
			
			System.out.println(fileUrl);
				*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileup;
	}
	@RequestMapping(value="del")
	public @ResponseBody Result del(String finalName,HttpServletRequest request){
		
		User user=operator.getUser();
		
		if (finalName.contains("\\"))
			 finalName=finalName.substring(finalName.indexOf("\\")+1);
	    //System.out.println(finalName);
		String fileUrl = "";
		Fileup fileup=new Fileup();
		//fileup.setFinalName(finalName);
		fileup=commonService.get(fileup.getClass(),finalName);
		Result result=new Result();
		if(null!=fileup)
		{
			if (fileup.getCreatorCode().equals(user.getClass())||user.getRoleId().equals("001"))
			{
				String path=request.getSession().getServletContext().getRealPath("/");
				path=path+File.separator+fileup.getPath()+finalName;
				File file = new File(path);
				if (!file.exists()) {
		        	result.setCode(1);
		        	result.setMsg("删除失败，文件不存在");
		        } else {
		        	  if (file.delete()) {
		        		  result.setCode(0);
		        		  result.setMsg("删除成功");
		        	  }
		        }
			}
			else
			{
				result.setCode(1);
	        	result.setMsg("删除失败，没有权限");
			}
			
		}
		//System.out.println(file.getAbsolutePath());

		
        	
        commonService.delete(fileup);
		
		
		
		return result;
	}
	
}
